package com.yanq.liancar.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vondear.rxtool.view.RxToast;

import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.SmallBPayAdapter;
import com.yanq.liancar.bean.PayNowBean;
import com.yanq.liancar.bean.PayResult;
import com.yanq.liancar.bean.ServiceAliPayBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatPayBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SmallBPaymentActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_pay_name)
    TextView tvPayName;
    @BindView(R.id.tv_pay_price)
    TextView tvPayPrice;
    @BindView(R.id.pay_recycleview)
    RecyclerView payRecycleview;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_CustomerService)
    TextView tvCustomerService;

    private List<PayNowBean> payNowBeanList = new ArrayList<>();
    private SmallBPayAdapter adapter;
    private int type = 1;
    private IWXAPI api;
    private String goodID, addressID, goodNum, price, buyers_note, oNum;
    private static final int SDK_PAY_FLAG = 1;
    private static final String APP_ID = "wxd2e19fc6b6f17ec0";
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**

                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。

                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtils.e("resultInfo====", resultInfo);
                    LogUtils.e("resultStatus====", resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        RxToast.success("下单成功");
                        finish();
                        //                        Bundle bundle=new Bundle();
                        //                        bundle.putString("orderID",orderID);
                        //                        RxActivityTool.skipActivityAndFinish(SmallBPaymentActivity.this,PurchaseSuccessActivity.class,bundle);
                    } else {

                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        RxToast.error("支付失败");
                    }
                    break;
                }

            }

        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, APP_ID);
        api.registerApp(APP_ID);
        setContentView(R.layout.activity_smallb_payment);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        mTvTitle.setText("在线支付");
        Bundle bundle = getIntent().getExtras();
        price = bundle.getString("price");
        tvPayPrice.setText(price);
        goodID = bundle.getString("goodID");
        addressID = bundle.getString("addressID");
        goodNum = bundle.getString("goodNum");
        tvPayName.setText(bundle.getString("goodname"));
        buyers_note = bundle.getString("buyers_note");
        if (!"".equals(getIntent().getExtras().getString("order_num"))) {
            oNum = getIntent().getExtras().getString("order_num");
        }
        initData();
        initRecyclerView();
    }

    private void initData() {
        PayNowBean bean = new PayNowBean();
        bean.setNum(1);
        bean.setName("支付宝支付");
        bean.setChecked(true);
        payNowBeanList.add(bean);
        PayNowBean bean2 = new PayNowBean();
        bean2.setNum(2);
        bean2.setName("微信支付");
        bean2.setChecked(false);
        payNowBeanList.add(bean2);
    }

    private void initRecyclerView() {
        payRecycleview.setNestedScrollingEnabled(false);
        payRecycleview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SmallBPayAdapter(R.layout.item_small_b_pay, payNowBeanList);
        payRecycleview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < payNowBeanList.size(); i++) {
                    if (position == i) {
                        payNowBeanList.get(i).setChecked(true);
                        type = payNowBeanList.get(position).getNum();
                    } else {
                        payNowBeanList.get(i).setChecked(false);
                    }
                }
                adapter.setNewData(payNowBeanList);
            }
        });
    }

    @OnClick({R.id.tv_pay, R.id.tv_CustomerService})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_CustomerService:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4008055011"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.tv_pay:
                if (type == 1) {
                    AliPayment();
                } else {
                    WeChatPayment();
                }
                break;
        }
    }

    //支付接口
    private void AliPayment() {
        OkGo.<String>post(Config.s + "llc/api/goodsAliPay")
                .tag(this)
                .params("token", UserBean.getbToken(this))
                .params("orderType", 3)
                .params("order_price", price.replace("¥", ""))
                .params("buyers_note", buyers_note)
                .params("goodsid", goodID)
                .params("id", addressID)
                .params("order_goods_num", goodNum)
                .params("pay_type", type)
                .params("oNum", oNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        final ServiceAliPayBean baseBean = gson.fromJson(response.body(), ServiceAliPayBean.class);
                        if (baseBean.isIsSuccess()) {
                            final String info = baseBean.getData().getSigned_content();
                            LogUtils.e("加签info===", info);
                            if ("".equals(info) || !TextUtils.isEmpty(info)) {
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(SmallBPaymentActivity.this);
                                        Map<String, String> result = alipay.payV2(info, true);

                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        mHandler.sendMessage(msg);
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            }
                        } else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }
                });
    }

    //微信支付
    private void WeChatPayment() {
        OkGo.<String>post(Config.s + "llc/api/goodsWXPay")
                .tag(this)
                .params("token", UserBean.getbToken(this))
                .params("orderType", 3)
                .params("order_price", price.replace("¥", ""))
                .params("buyers_note", buyers_note)
                .params("goodsid", goodID)
                .params("id", addressID)
                .params("order_goods_num", goodNum)
                .params("pay_type", type)
                .params("oNum", oNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        WeChatPayBean baseBean = gson.fromJson(response.body(), WeChatPayBean.class);
                        if (baseBean.isIsSuccess()) {
                            PayReq request = new PayReq();
                            request.appId = baseBean.getData().getAppid();
                            request.partnerId = baseBean.getData().getPartnerId();
                            request.prepayId = baseBean.getData().getPrepayId();
                            request.packageValue = baseBean.getData().getPackageValue();
                            request.nonceStr = baseBean.getData().getNonceStr();
                            request.timeStamp = baseBean.getData().getTimeStamp();
                            request.sign = baseBean.getData().getSign();
                            api.sendReq(request);
                            LogUtils.e(" api.sendReq=====", api.sendReq(request) + "");
                        } else {
                            RxToast.error("支付失败，请联系客服");
                            finish();
                        }
                    }


                });


        //        String order_id=Utils.md5(UUID.randomUUID().toString().replace("_","")+System.currentTimeMillis());
        //        Log.e("dadadassda", price.replace("¥",""));
        //        WechatPayTools.wechatPayUnifyOrder(mContext,
        //            "wxd2e19fc6b6f17ec0", //微信分配的APP_ID
        //            "1513987451", //微信分配的 PARTNER_ID (商户ID)
        //            "042732fcd9da459da435cdffba5bd01d", //微信分配的 PRIVATE_KEY (私钥)
        //            new WechatModel(order_id, //订单ID (唯一)
        //                            price.replace("¥",""), //价格
        //                        tvPayName.getText().toString().trim(), //商品名称
        //                        "qqqqqqq"), //商品描述详情
        //                                new OnSuccessAndErrorListener() {
        //        @Override
        //        public void onSuccess(String s) {
        //            RxToast.success(s);
        //        }
        //
        //        @Override
        //        public void onError(String s) {
        //            RxToast.error(s);
        //        }
        //    });

    }

}




